package com.sdcs.server.daoimpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sdcs.server.model.Homework;

@Component
public class HomeworkDaoImpl {
	@Autowired
	private SessionFactory sessionFactory;
	
	public void delete(String id) {
		Session sess = null;
		Transaction tx = null;
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			String hql = " delete Homework where homework_id = ?"; 
			sess.createQuery(hql).setParameter(0, id).executeUpdate();
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
	}
	
	public void save(Homework object){
		Session sess = null;
		Transaction tx = null;
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			sess.save(object);
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
	}
	
	public List<Homework> getMyInfo(String teacher_id) {
		Session sess = null;
		Transaction tx = null;
		List<Homework> list = new ArrayList<Homework>();
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			String hql= "from Homework where teacher_id = ?";
			list = sess.createQuery(hql, Homework.class).setParameter(0, teacher_id).getResultList();
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
		
		return list;
	}
	
	public List<Homework> getAll() {
		Session sess = null;
		Transaction tx = null;
		List<Homework> list = new ArrayList<Homework>();
		
		try {
			sess = sessionFactory.openSession();
			tx = sess.beginTransaction();
			
			String hql= "from Homework order by homework_id desc";
			list = sess.createQuery(hql, Homework.class).getResultList();
			
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
		} finally {
			if (sess != null) {
				sess.close();
			}
		}
		
		return list;
	}
}
